<?php
App::uses('AppController', 'Controller');
/**
 * Documents Controller
 *
 * @property Document $Document
 */
class DocumentsController extends AppController {


/**
 * index method
 *
 * @return void
 */
	public function application() {
		// обрабатываем id абитуриента
		$abiturient_id = $this->request['named']['abiturient'];
		$this->set('abiturient_id', $abiturient_id);
		// подключаем модель Abiturient 
		$this->loadModel('Abiturient');
		$abiturient = $this->Abiturient->find('first', array('conditions' => array('Abiturient.id' => $abiturient_id)));
		$this->set('abiturient', $abiturient);
		//debug($abiturient);
		// подключаем модель Citizenship 
		$this->loadModel('Citizenship');
		$citizenships = $this->Citizenship->find('list');
		$this->set(compact('citizenships'));
		// подключаем модель Subject
		$this->loadModel('Subject');
		$subjects = $this->Subject->find('list');
		$this->set('subjects', $subjects);
		// выбираем все желаемые специальности абитуриента с упорядочиванием по Selectedprofession.id
		$selectedprofessions = $this->Abiturient->Selectedprofession->find('all', array('conditions' => array('Selectedprofession.abiturient_id' => $abiturient_id), 'order' => array('Selectedprofession.id')));
		$this->set('selectedprofessions', $selectedprofessions);
		// подключаем модель Profession
		$this->loadModel('Profession');
		$professions = $this->Profession->find('list');
		$this->set('professions', $professions);
		// подключаем модель Learningform
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this-> set('learningforms',$learningforms);
		// подключаем модель Learningtype
		$this->LoadModel('Learningtype');
		$learningtypes=$this->Learningtype->find('all');
		$this->set('learningtypes',$learningtypes);
		// подключаем модель Resulttype
		$this->loadModel('Resulttype');
		$resulttypes = $this->Resulttype->find('list');
		$this->set('resulttypes', $resulttypes);		
		// подключаем модель Educationdoctype
		$this->loadModel('Educationdoctype');
		$educationdoctypes = $this->Educationdoctype->find('list');
		$this->set('educationdoctypes', $educationdoctypes);
		
		
		$this->LoadModel('Foreignlanguage');
		$foreignlanguages=$this->Foreignlanguage->find('list');
		$this->set('foreignlanguages',$foreignlanguages);
		
		
		// подключаем модель Resulttype
		$this->loadModel('Privilege');
		$privileges = $this->Privilege->find('list');
		$this->set('privileges', $privileges);
		
		// убираем debug
		Configure::write('debug', 0);
		// выводим в пустой шаблон
		 $this->layout = 'blank';
		//$this->render('/','blank','application');
	}
	
/**
 *  listofdocuments выводит опись документов абитуриента
 * 
 */
	public function listofdocuments() {
		// обрабатываем id абитуриента
		$abiturient_id = $this->request['named']['abiturient'];
		$this->set('abiturient_id', $abiturient_id);
		// подключаем модель Abiturient
		$this->loadModel('Abiturient');
		$abiturient = $this->Abiturient->find('first', array('conditions' => array('Abiturient.id' => $abiturient_id)));
		$this->set('abiturient', $abiturient);
		$profession_id = $abiturient['Selectedprofession'][0]['profession_id'];
		// подключаем модель Profession
		$this->loadModel('Profession');
		$profession = $this->Profession->find('first', array('conditions' => array('Profession.id' => $profession_id), 'recursive' => -1, 'fields' => array('Profession.id', 'Profession.facultet_id')));
		$this->set('profession', $profession);
		$professions =  $this->Profession->find('list');
		$this->set(compact('professions'));
		// подключаем модель Educationdoctype
		$this->loadModel('Educationdoctype');
		$educationdoctypes = $this->Educationdoctype->find('list');
		$this->set('educationdoctypes', $educationdoctypes);
		// подключаем модель Facultet
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);		
		
		$this->layout = 'blank';
	}

/**
 *  abiturientsdigits выводит количество заявлений по специальностям по факультетам
 * 
 */
	public function abiturientsdigits() {
		// подключаем модель Educationlevel
		$this->loadModel('Educationlevel');
		$educationlevels = $this->Educationlevel->find('list');
		$this->set('educationlevels', $educationlevels);
		$tmpeducationlevels = $this->Educationlevel->find('all', array('recursive' => -1, 'fields' => array('Educationlevel.id')));
		//$this->set('tmpeducationlevels', $tmpeducationlevels);
		// подключаем модель Facultet
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		
		//$this->set('tmpfacultets', $tmpfacultets);
		// подключаем модель Profession
		$this->loadModel('Profession');
		$professions =  $this->Profession->find('list');
		$this->set(compact('professions'));

		//$this->set('tmpprofessions', $tmpprofessions);		
		// подключаем модель Learningform
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this-> set('learningforms',$learningforms);
		$tmplearningforms = $this->Learningform->find('all', array('recursive' => -1, 'fields' => array('Learningform.id')));
		//$this->set('tmplearningforms', $tmplearningforms);		
		// подключаем модель Learningtype
		$this->LoadModel('Learningtype');
		$learningtypes=$this->Learningtype->find('list');
		$this->set('learningtypes',$learningtypes);
		$tmplearningtypes = $this->Learningtype->find('all', array('recursive' => -1, 'fields' => array('Learningtype.id')));
		//$this->set('tmplearningtypes', $tmplearningtypes);
		
		// подключаем модель Selectedprofession
		$this->loadModel('Selectedprofession');
		// для выбора количества мест
		$this->loadModel('Targetdigit');
				
		// подключаем модель Abiturient
		$this->loadModel('Abiturient');
		$abiturients = $this->Abiturient->find('all', array('conditions' => array(
				'Abiturient.prepared' => 1,
				'Abiturient.approved' => 1,
				'Abiturient.enrolled' => 0,
				'Abiturient.canceled' => 0
				
				), 'recursive' => -1, 'fields' => array('Abiturient.id')));
		
		$abiturients_ids = array();
		
		foreach ($abiturients as $abiturient):
			array_push($abiturients_ids, $abiturient['Abiturient']['id']);
		endforeach;

		$totalabiturientsdigits = array();
		foreach ($tmpeducationlevels as $educationlevel):
			$tmpfacultets = $this->Facultet->find('all', array('conditions' =>array('Facultet.educationlevel_id' => $educationlevel['Educationlevel']['id']), 'recursive' => -1, 'fields' => array('Facultet.id')));
			foreach ($tmpfacultets as $facultet):
			$tmpprofessions = $this->Profession->find('all', array('conditions' =>array('Profession.facultet_id' => $facultet['Facultet']['id']), 'recursive' => -1, 'fields' => array('Profession.id')));
				foreach ($tmpprofessions as $profession):
					foreach ($tmplearningforms as $learningform):
						foreach ($tmplearningtypes as $learningtype):
							$selectedprofessioncount = $this->Selectedprofession->find('count', array('conditions' => 
									array(
											'Selectedprofession.profession_id' => $profession['Profession']['id'],
											'Selectedprofession.abiturient_id' => $abiturients_ids,
											'Selectedprofession.learningform_id' => $learningform['Learningform']['id'],
											'Selectedprofession.learningtype_id' => $learningtype['Learningtype']['id'],
											), 'recursive' =>-1));
							
							//debug ($selectedprofessioncount);
							// выбираем количество мест по бюджету и внебюджету если 
							// если и бюжет и внебюджет ноль то строку специальность форма и тип обучения пропускаем
							$targetdigits_b = '';
							$targetdigits_vb = '';
							
							$targetdigits_b = $this->Targetdigit->find('all', array('conditions' => array(
									'Targetdigit.profession_id' => $profession['Profession']['id'],
									'Targetdigit.learningform_id' => $learningform['Learningform']['id'],
									'Targetdigit.learningtype_id' => 1
									
							), 'recursive' => -1, 'fields' => array('Targetdigit.digits')));
							//debug ($targetdigits_b);
							$targetdigits_vb = $this->Targetdigit->find('all', array('conditions' => array(
									'Targetdigit.profession_id' => $profession['Profession']['id'],
									'Targetdigit.learningform_id' => $learningform['Learningform']['id'],
									'Targetdigit.learningtype_id' => 2
										
							), 'recursive' => -1, 'fields' => array('Targetdigit.digits')));			
							//debug ($targetdigits_vb);				
							if (empty($targetdigits_b[0]['Targetdigit']['digits']) && empty($targetdigits_vb[0]['Targetdigit']['digits']))
							{
								continue;
							} else {
								$digits = 0; 
								if ($learningtype['Learningtype']['id'] == 1) {
									if (!empty($targetdigits_b[0]['Targetdigit']['digits'])) {
										$digits = $targetdigits_b[0]['Targetdigit']['digits'];
									}
								} else {
									if (!empty($targetdigits_vb[0]['Targetdigit']['digits'])) {
										$digits = $targetdigits_vb[0]['Targetdigit']['digits'];
									}
								}
								array_push($totalabiturientsdigits,
								array(	'educationlevel' =>$educationlevel['Educationlevel']['id'],
								'facultet' => $facultet['Facultet']['id'],
								'profession' => $profession['Profession']['id'],
								'learnigform' => $learningform['Learningform']['id'],
								'learnigtype' => $learningtype['Learningtype']['id'],
								'digits' => $digits,
								'applicationcount' => $selectedprofessioncount
								));								
							}

						endforeach;
					endforeach;
				endforeach;
			endforeach;
		endforeach;
		$this->set('totalabiturientsdigits',$totalabiturientsdigits);
		
		$this->layout = 'blank';
	}
	
/** *********************************************************************************************
 * 
 * checkabiturientslist пофамильный список абитуриентов с заявлениями для проверки по факультетам
 * 
 * *********************************************************************************************/	
	public function checkabiturientslist() {
		// подключаем модель Educationlevel
		$this->loadModel('Educationlevel');
		$educationlevels = $this->Educationlevel->find('list');
		$this->set('educationlevels', $educationlevels);
		$tmpeducationlevels = $this->Educationlevel->find('all', array('recursive' => -1, 'fields' => array('Educationlevel.id')));
		//$this->set('tmpeducationlevels', $tmpeducationlevels);
		// подключаем модель Facultet
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		
		//$this->set('tmpfacultets', $tmpfacultets);
		// подключаем модель Profession
		$this->loadModel('Profession');
		$professions =  $this->Profession->find('list');
		$this->set(compact('professions'));
		
		//$this->set('tmpprofessions', $tmpprofessions);
		// подключаем модель Learningform
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this-> set('learningforms',$learningforms);
		$tmplearningforms = $this->Learningform->find('all', array('recursive' => -1, 'fields' => array('Learningform.id')));
		//$this->set('tmplearningforms', $tmplearningforms);
		// подключаем модель Learningtype
		$this->LoadModel('Learningtype');
		$learningtypes=$this->Learningtype->find('list');
		$this->set('learningtypes',$learningtypes);
		$tmplearningtypes = $this->Learningtype->find('all', array('recursive' => -1, 'fields' => array('Learningtype.id')));
		//$this->set('tmplearningtypes', $tmplearningtypes);
		
		// подключаем модель Resulttype
		$this->loadModel('Resulttype');
		$resulttypes = $this->Resulttype->find('list');
		$this->set('resulttypes', $resulttypes);	
			
		// подключаем модель Subject
		$this->loadModel('Subject');
		$subjects = $this->Subject->find('list');
		$this->set('subjects', $subjects);
		
		// подключаем модель Subject
		$this->loadModel('Tgintakeorg');
		$tgintakeorgs = $this->Tgintakeorg->find('list');
		$this->set('tgintakeorgs', $tgintakeorgs);
		
		// выбираем все минимальные результаты по всем предметам
		$this->loadModel('Minimalresult');
		$minimalresults = $this->Minimalresult->find('all', array('recursive' => -1));
		$this->set('minimalresults', $minimalresults);
		
		// подключаем модель Selectedprofession
		$this->loadModel('Selectedprofession');
		// подключаем модель Abiturient
		$this->loadModel('Abiturient');
		
		$abiturientslist  = array();
		foreach ($tmpeducationlevels as $educationlevel):
			$tmpfacultets = $this->Facultet->find('all', array('conditions' =>array('Facultet.educationlevel_id' => $educationlevel['Educationlevel']['id']), 'recursive' => -1, 'fields' => array('Facultet.id')));
			foreach ($tmpfacultets as $facultet):
				$tmpprofessions = $this->Profession->find('all', array('conditions' =>array('Profession.facultet_id' => $facultet['Facultet']['id']), 'recursive' => -1, 'fields' => array('Profession.id')));
				foreach ($tmpprofessions as $profession):
					foreach ($tmplearningforms as $learningform):
						foreach ($tmplearningtypes as $learningtype):
							$abiturientsselectedprofessions = $this->Selectedprofession->find('all', array('conditions' =>
												array(
												'Selectedprofession.profession_id' => $profession['Profession']['id'],
												'Selectedprofession.learningform_id' => $learningform['Learningform']['id'],
												'Selectedprofession.learningtype_id' => $learningtype['Learningtype']['id'],
												), 'recursive' =>-1, 'fields' =>array('Selectedprofession.abiturient_id')));
							//debug($abiturientsselectedprofessions);
							foreach ($abiturientsselectedprofessions as $abiturientsselectedprofession):
								$abiturient = $this->Abiturient->find('first', array('conditions' => array('Abiturient.id' =>$abiturientsselectedprofession['Selectedprofession']['abiturient_id'])));
				 				array_push($abiturientslist,
								array(	'educationlevel' =>$educationlevel['Educationlevel']['id'],
										'facultet' => $facultet['Facultet']['id'],
										'profession' => $profession['Profession']['id'],
										'learningform' => $learningform['Learningform']['id'],
										'learningtype' => $learningtype['Learningtype']['id'],
										'abiturient_id' => $abiturient['Abiturient']['id'],
										'abiturient_fio'=> $abiturient['Abiturient']['lastname'].' '.$abiturient['Abiturient']['firstname'].' '.$abiturient['Abiturient']['surname'],
										'edudoc_original' => $abiturient['Abiturient']['originaleducationdoc'],
										'tgintake' => $abiturient['Targetingintake'],
										'privileges' => $abiturient['Privilege'],
										'other_selprofs' => $abiturient['Selectedprofession'],
										'results' => $abiturient['Result']
										
								)); 
							endforeach;
						endforeach;
					endforeach;
				endforeach;
			endforeach;
		endforeach;
		$this->set('abiturientslist',$abiturientslist);
		$this->layout = 'blank';		
	}
	
/** *********************************************************************************
 *  выводит пофамильный список абитуриентов на факультете отсортированный по алфавиту
 ***********************************************************************************/	
	public function abiturientsabcmanual() {
		$facultet_id = $this->request['data']['Document']['facultet_id'];
		$this->set('facultet_id', $facultet_id);
		$profession_id = $this->request['data']['Document']['profession_id'];
		$this->set('profession_id', $profession_id);
		$learningform_id = $this->request['data']['Document']['learningform_id'];
		$this->set('learningform_id', $learningform_id);
		$learningtype_id = $this->request['data']['Document']['learningtype_id'];
		$this->set('learningtype_id', $learningtype_id);
		
		// подключаем модель Learningform
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this-> set('learningforms',$learningforms);

		// подключаем модель Learningtype
		$this->LoadModel('Learningtype');
		$learningtypes=$this->Learningtype->find('list');
		$this->set('learningtypes',$learningtypes);
		
		// подключаем модель Profession
		$this->loadModel('Profession');
		$professions =  $this->Profession->find('list');
		$this->set(compact('professions'));

		// подключаем модель Facultet
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		
		// подключаем модель Selectedprofession
		$this->loadModel('Selectedprofession');
		// подключаем модель Abiturient
		$this->loadModel('Abiturient');
		
		$abiturients_ids = $this->Selectedprofession->find('all', array('conditions' => array('Selectedprofession.profession_id' => $profession_id,
				'Selectedprofession.learningform_id' => $learningform_id,
				'Selectedprofession.learningtype_id' => $learningtype_id), 'recursive' => -1, 'fields' => array('Selectedprofession.abiturient_id')));
		$ids = array();
		foreach ($abiturients_ids as $abiturient_id):
			array_push($ids, $abiturient_id['Selectedprofession']['abiturient_id']);
		endforeach;
		
		$abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.id' => $ids, 'Abiturient.prepared' => 1, 'Abiturient.approved' => 1, 'Abiturient.enrolled' => 0, 'Abiturient.canceled' => 0), 
				'recursive' => -1, 
				'order' => 'Abiturient.lastname asc', 
				'fields' => array('Abiturient.lastname', 'Abiturient.firstname', 'Abiturient.surname')));
		
		$this->set('abiturients', $abiturients);
		
		$this->layout = 'blank';
	}
	
	/** *********************************************************************************
	 * генерирует csv файл для мобильного приложения
	 * 
	 * *********************************************************************************/
	public function mobilecsv () {
		// подключаем модель Educationlevel
		$this->loadModel('Educationlevel');
		$educationlevels = $this->Educationlevel->find('list');
		$this->set('educationlevels', $educationlevels);
		$tmpeducationlevels = $this->Educationlevel->find('all', array('recursive' => -1, 'fields' => array('Educationlevel.id')));
		//$this->set('tmpeducationlevels', $tmpeducationlevels);
		// подключаем модель Facultet
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		
		//$this->set('tmpfacultets', $tmpfacultets);
		// подключаем модель Profession
		$this->loadModel('Profession');
		$professions =  $this->Profession->find('list');
		$this->set(compact('professions'));
		
		//$this->set('tmpprofessions', $tmpprofessions);
		// подключаем модель Learningform
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this-> set('learningforms',$learningforms);
		$tmplearningforms = $this->Learningform->find('all', array('recursive' => -1, 'fields' => array('Learningform.id')));
		//$this->set('tmplearningforms', $tmplearningforms);
		// подключаем модель Learningtype
		$this->LoadModel('Learningtype');
		$learningtypes=$this->Learningtype->find('list');
		$this->set('learningtypes',$learningtypes);
		$tmplearningtypes = $this->Learningtype->find('all', array('recursive' => -1, 'fields' => array('Learningtype.id')));
		//$this->set('tmplearningtypes', $tmplearningtypes);
		
		// подключаем модель Selectedprofession
		$this->loadModel('Selectedprofession');
		// подключаем модель Abiturient
		$this->loadModel('Abiturient');
		
		$abiturientslist  = array();
		
		foreach ($tmpeducationlevels as $educationlevel):
			$abiturientslist[$educationlevel['Educationlevel']['id']] = array();
			$tmpfacultets = $this->Facultet->find('all', array('conditions' =>array('Facultet.educationlevel_id' => $educationlevel['Educationlevel']['id']), 'recursive' => -1, 'fields' => array('Facultet.id', 'Facultet.educationlevel_id')));
			foreach ($tmpfacultets as $facultet):
				$tmpprofessions = $this->Profession->find('all', array('conditions' =>array('Profession.facultet_id' => $facultet['Facultet']['id']), 'recursive' => -1, 'fields' => array('Profession.id')));
				foreach ($tmpprofessions as $profession):
					$abiturientslist[$educationlevel['Educationlevel']['id']][$profession['Profession']['id']] = array();
					foreach ($tmplearningforms as $learningform):
						$abiturientslist[$educationlevel['Educationlevel']['id']][$profession['Profession']['id']][$learningform['Learningform']['id']] = array();
						foreach ($tmplearningtypes as $learningtype):
							$abiturientslist[$educationlevel['Educationlevel']['id']][$profession['Profession']['id']][$learningform['Learningform']['id']][$learningtype['Learningtype']['id']] = array();
						endforeach;
					endforeach;
				endforeach;
			endforeach;
		endforeach;
		
		//debug ($abiturientslist);
		
		
		$abiturients_ids = $this->Abiturient->find('all', array ('conditions' => array(
				'Abiturient.prepared' => 1,
				'Abiturient.approved' => 1,
				'Abiturient.enrolled' => 0,
				'Abiturient.canceled' => 0
					
		), 'recursive' => -1,'fields' => array('Abiturient.id','Abiturient.lastname', 'Abiturient.firstname', 'Abiturient.surname' ) ));
		
		foreach ($abiturients_ids as $abiturient_id):
			$abiturient_selprofs = $this->Selectedprofession->find('all', array('conditions' => array('Selectedprofession.abiturient_id' => $abiturient_id['Abiturient']['id']), 'recursive' => -1, 'order' => 'Selectedprofession.id'));
			
				
			// проверяем есть ли у абитуриента льгота
			$is_privilege = $this->Abiturient->AbiturientsPrivilege->find('count', array('conditions' => array('AbiturientsPrivilege.abiturient_id' =>$abiturient_id['Abiturient']['id'])));
				
			// проверяем есть ли у абитуриента оценки ФЦТ
			$is_fct = $this->Abiturient->Result->find('count', array('conditions' => array('Result.abiturient_id' => $abiturient_id['Abiturient']['id'], 'Result.resulttype_id' => 2)));
				
			
			$first_selprof = 0;
			foreach ($abiturient_selprofs as $selprof):
				$first_selprof++;
				$fio = $abiturient_id['Abiturient']['lastname'].' '.$abiturient_id['Abiturient']['firstname'].' '.$abiturient_id['Abiturient']['surname'];
				// если льгота
				if (($first_selprof == 1) && $is_privilege) {
					$fio .= ' (вне конкурса)';
				}
				if ($is_fct) {
					$fio .= ' (вступительные испытания в ВУЗе)';
				}
				$edulevel = 0;
				if ($selprof['Selectedprofession']['profession_id'] <13) {
					$edulevel = 1;
				} else {
					$edulevel = 2;
				}
				array_push($abiturientslist[$edulevel][$selprof['Selectedprofession']['profession_id']][$selprof['Selectedprofession']['learningform_id']][$selprof['Selectedprofession']['learningtype_id']], $fio);
			endforeach;
		endforeach;
		
		
		$this->set('abiturientslist', $abiturientslist);
		
		$this->layout = 'blank';		
	}
	
	/** *********************************************************************************
	 *  выводит пофамильный список абитуриентов по вузу отсортированный по алфавиту
	 *
	 * *********************************************************************************/
	public function abiturientsabc() {
		// подключаем модель Educationlevel
		$this->loadModel('Educationlevel');
		$educationlevels = $this->Educationlevel->find('list');
		$this->set('educationlevels', $educationlevels);
		$tmpeducationlevels = $this->Educationlevel->find('all', array('recursive' => -1, 'fields' => array('Educationlevel.id')));
		//$this->set('tmpeducationlevels', $tmpeducationlevels);
		// подключаем модель Facultet
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		
		//$this->set('tmpfacultets', $tmpfacultets);
		// подключаем модель Profession
		$this->loadModel('Profession');
		$professions =  $this->Profession->find('list');
		$this->set(compact('professions'));
		
		//$this->set('tmpprofessions', $tmpprofessions);
		// подключаем модель Learningform
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this-> set('learningforms',$learningforms);
		$tmplearningforms = $this->Learningform->find('all', array('recursive' => -1, 'fields' => array('Learningform.id')));
		//$this->set('tmplearningforms', $tmplearningforms);
		// подключаем модель Learningtype
		$this->LoadModel('Learningtype');
		$learningtypes=$this->Learningtype->find('list');
		$this->set('learningtypes',$learningtypes);
		$tmplearningtypes = $this->Learningtype->find('all', array('recursive' => -1, 'fields' => array('Learningtype.id')));
		//$this->set('tmplearningtypes', $tmplearningtypes);
		
		// подключаем модель Selectedprofession
		$this->loadModel('Selectedprofession');
		// подключаем модель Abiturient
		$this->loadModel('Abiturient');
		
		$abiturientslist  = array();
		
		foreach ($tmpeducationlevels as $educationlevel):
			$abiturientslist[$educationlevel['Educationlevel']['id']] = array();
			$tmpfacultets = $this->Facultet->find('all', array('conditions' =>array('Facultet.educationlevel_id' => $educationlevel['Educationlevel']['id']), 'recursive' => -1, 'fields' => array('Facultet.id', 'Facultet.educationlevel_id')));
			foreach ($tmpfacultets as $facultet):
				$tmpprofessions = $this->Profession->find('all', array('conditions' =>array('Profession.facultet_id' => $facultet['Facultet']['id']), 'recursive' => -1, 'fields' => array('Profession.id')));
				foreach ($tmpprofessions as $profession):
				$abiturientslist[$educationlevel['Educationlevel']['id']][$profession['Profession']['id']] = array();
					foreach ($tmplearningforms as $learningform):
					$abiturientslist[$educationlevel['Educationlevel']['id']][$profession['Profession']['id']][$learningform['Learningform']['id']] = array();
						foreach ($tmplearningtypes as $learningtype):
						$abiturientslist[$educationlevel['Educationlevel']['id']][$profession['Profession']['id']][$learningform['Learningform']['id']][$learningtype['Learningtype']['id']] = array();
						endforeach;
					endforeach;
				endforeach;
			endforeach;
		endforeach;
						
		//debug ($abiturientslist);
		
		
		$abiturients_ids = $this->Abiturient->find('all', array ('conditions' => array(
					'Abiturient.prepared' => 1,
					'Abiturient.approved' => 1,
					'Abiturient.enrolled' => 0,
					'Abiturient.canceled' => 0
			
			), 'recursive' => -1,'fields' => array('Abiturient.id','Abiturient.lastname', 'Abiturient.firstname', 'Abiturient.surname' ) ));
		
		foreach ($abiturients_ids as $abiturient_id):
			$abiturient_selprofs = $this->Selectedprofession->find('all', array('conditions' => array('Selectedprofession.abiturient_id' => $abiturient_id['Abiturient']['id']), 'recursive' => -1, 'order' => 'Selectedprofession.id'));
		
			
			// проверяем есть ли у абитуриента льгота
			$is_privilege = $this->Abiturient->AbiturientsPrivilege->find('count', array('conditions' => array('AbiturientsPrivilege.abiturient_id' =>$abiturient_id['Abiturient']['id'])));
			
			// проверяем есть ли у абитуриента оценки ФЦТ
			$is_fct = $this->Abiturient->Result->find('count', array('conditions' => array('Result.abiturient_id' => $abiturient_id['Abiturient']['id'], 'Result.resulttype_id' => 2)));
			
		
			$first_selprof = 0;	
			foreach ($abiturient_selprofs as $selprof):
			 $first_selprof++;
				$fio = $abiturient_id['Abiturient']['lastname'].' '.$abiturient_id['Abiturient']['firstname'].' '.$abiturient_id['Abiturient']['surname'];
				// если льгота
				if (($first_selprof == 1) && $is_privilege) {
					$fio .= ' (вне конкурса)';
				}
				if ($is_fct) {
					$fio .= ' (вступительные испытания в ВУЗе)';
				}
				$edulevel = 0;
				if ($selprof['Selectedprofession']['profession_id'] <13) {
					$edulevel = 1;
				} else {
					$edulevel = 2;
				}
			array_push($abiturientslist[$edulevel][$selprof['Selectedprofession']['profession_id']][$selprof['Selectedprofession']['learningform_id']][$selprof['Selectedprofession']['learningtype_id']], $fio);
			endforeach;
		endforeach;

		
		$this->set('abiturientslist', $abiturientslist);
		
		$this->layout = 'blank';						
	}		
	
	public function abiturientstofbs() {
		
		// подключаем модель Abiturient
		$this->loadModel('Abiturient');
		$without_scores = $this->request->data['Document']['without_scores'];
		
		$this->set('without_scores', $without_scores);
		// обрабатываем id абитуриента с которого нужно начинат выгрузку
		$abiturient_id = $this->request->data['Document']['abiturient'];
		if ($abiturient_id == '' ) {
			$abiturients = $this->Abiturient->find('all', array('conditions' => array(
					'Abiturient.prepared' => 1,
					'Abiturient.approved' => 1,
					'Abiturient.enrolled' => 0,
					'Abiturient.canceled' => 0
			
			), 'fields' => array('Abiturient.lastname', 'Abiturient.firstname', 'Abiturient.surname',  'Abiturient.passport_ser', 'Abiturient.passport_num')));	
		} 
		
		else {
			$abiturients = $this->Abiturient->find('all', array('conditions' => array(
					'Abiturient.id >= ' => $abiturient_id,
					'Abiturient.prepared' => 1,
					'Abiturient.approved' => 1,
					'Abiturient.enrolled' => 0,
					'Abiturient.canceled' => 0
						
			), 'fields' => array('Abiturient.lastname', 'Abiturient.firstname', 'Abiturient.surname', 'Abiturient.passport_ser', 'Abiturient.passport_num')));			
		}	
		$this->set('abiturients', $abiturients);
		$this->layout = 'blank';
	}
	
	public function tgintakeorgsabcount() {
		$this->loadModel('Tgintakeorg');
		$tgintakeorgs = $this->Tgintakeorg->find('all');
		
		$this->loadModel('Abiturient');
		$tgorgslist = array();
		foreach ($tgintakeorgs as $tgintakeorg):
			$tgorglist = array();
			$tgorglist['count'] = count($tgintakeorg['Targetingintake']);
			$tgorglist['org'] = $tgintakeorg['Tgintakeorg']['name'];
			$tgintakes = $tgintakeorg['Targetingintake'];
			$abiturients_fio = array();
			foreach ($tgintakes as $tgintake):
				$abiturient_fio = $this->Abiturient->find('all', array('conditions' => array('Abiturient.id' => $tgintake['abiturient_id']), 'recursive' => -1, 'fields' => array('Abiturient.lastname', 'Abiturient.firstname', 'Abiturient.surname')));
				//debug($abiturient_fio);
				array_push($abiturients_fio, $abiturient_fio[0]['Abiturient']['lastname'].' '.$abiturient_fio[0]['Abiturient']['firstname'].' '.$abiturient_fio[0]['Abiturient']['surname']);
			endforeach;
			$tgorglist['abiturients'] = $abiturients_fio;
			// debug($abiturients_fio);
			array_push($tgorgslist, $tgorglist);
		endforeach;
		
		$this->set('tgorgslist', $tgorgslist);
		$this->layout = 'blank';
	}
/**
 *  разбираем пакетный файл полученный из фбс и генерируем файл с справками тем у кого a файле фбс ошибок нет
 * 
 */
	public function printfbsinfo() {
		if ($this->request->data['Document']['csvfile']['error'] == 0) {
			$fbsfile = $this->request->data['Document']['csvfile'];

			// начинаем обрабатывать пакетный файл полученный из ФБС 
			$csvfile = fopen($fbsfile['tmp_name'], "r");
			
			//читаем первую строку там заголовки
			$line = fgetcsv($csvfile, 100000, ";");
			//debug($line);
			// подключаем модель Abiturient
			$this->loadModel('Abiturient');
			
			// инициализируем массив ошибок
			$allerrors = array();
			
			// инициализируем массив справок абитуриентам
			$abiturients = array();
			
			// перебираем файл построчно до конца
			while ( !(feof($csvfile))){
				// читаем строку
				$line = fgetcsv($csvfile, 100000,  "%");
				//debug($line);
				// фиксируем номер свидетельства
				$egenumber = (iconv('Windows-1251', 'UTF-8',$line[0]));
				 // номер
				$passport_ser = (iconv('Windows-1251', 'UTF-8',$line[5]));
				// серию
				$passport_num = (iconv('Windows-1251', 'UTF-8',$line[6]));
				// год сертификата
				$egeyear =  $line[8];
				// если статус у свидетельства еге не действителен
				if ( (iconv('Windows-1251', 'UTF-8', $line[9])) != 'Действующий'){
					$tmperror = array('lastname' => (iconv('Windows-1251', 'UTF-8', $line[2])), 'firstname' => (iconv('Windows-1251', 'UTF-8', $line[3])), 'surname' => (iconv('Windows-1251', 'UTF-8', $line[4])), 'ser' => $line[5], 'num' => $line[6], 'status' => 'св-во не действительно или ошибка');
					array_push($allerrors, $tmperror);
				} else {
					// ищем данные абитуриента
					$abiturient = $this->Abiturient->find('all', array('conditions' => 
							array(	'Abiturient.passport_ser' => $passport_ser, 
									'Abiturient.passport_num' => $passport_num), 'recursive' => -1, 
							'fields' => array(	'Abiturient.id', 
												'Abiturient.lastname', 
												'Abiturient.firstname', 
												'Abiturient.surname')));
					// если абитуриент не найдем
					if (empty($abiturient)){
						$tmperror = array('lastname' => (iconv('Windows-1251', 'UTF-8', $line[2])), 'firstname' => (iconv('Windows-1251', 'UTF-8', $line[3])), 'surname' => (iconv('Windows-1251', 'UTF-8', $line[4])), 'ser' => $line[5], 'num' => $line[6], 'status' => 'абитуриент не найден');
						array_push($allerrors, $tmperror);
					} else {
						$russian = 0;
						$math = 0;
						$chemistry = 0;
						$biology = 0;
						$history = 0;
						$social = 0;
						// русский язык
						if (!empty($line[10])){
							$russian = $line[10];
						}	
						// математика
						if (!empty($line[12])){
							$math = $line[12];
						}		
						// химия
						if (!empty($line[16])){
							$chemistry = $line[16];
						}		
						// биология
						if (!empty($line[18])){
							$biology = $line[18];
						}			
						//  история
						if (!empty($line[20])){
							$history = $line[20];
						}				
						// обществознание
						if (!empty($line[30])){
							$social = $line[30];
						}																								
						/*
						 * // русский язык
						if (!empty($line[7])){
							$first_scobe = strpos($line[7], '(');
							$last_scobe = strrpos($line[7], ')');
							//debug($line[7]);
							$score = substr($line[7],$first_scobe+1,$last_scobe-$first_scobe-1);
							$score = explode(',', $score);
							$russian = $score;
						}
						// математика
						if (!empty($line[9])){
							$first_scobe = strpos($line[9], '(');
							$last_scobe = strrpos($line[9], ')');
							//debug($line[9]);
							$score = substr($line[9],$first_scobe+1,$last_scobe-$first_scobe-1);
							$score = explode(',', $score);
							$math = $score;
						}	
						// химия
						if (!empty($line[13])){
							$first_scobe = strpos($line[13], '(');
							$last_scobe = strrpos($line[13], ')');
							//debug($line[13]);
							$score = substr($line[13],$first_scobe+1,$last_scobe-$first_scobe-1);
							$score = explode(',', $score);
							$chemistry = $score;
						}	
						// биология
						if (!empty($line[15])){
							$first_scobe = strpos($line[15], '(');
							$last_scobe = strrpos($line[15], ')');
							//debug($line[15]);
							$score = substr($line[15],$first_scobe+1,$last_scobe-$first_scobe-1);
							$score = explode(',', $score);
							$biology = $score;
						}	
						//  история
						if (!empty($line[17])){
							$first_scobe = strpos($line[17], '(');
							$last_scobe = strrpos($line[17], ')');
							//debug($line[17]);
							$score = substr($line[17],$first_scobe+1,$last_scobe-$first_scobe-1);
							$score = explode(',', $score);
							$history = $score;
						}					
						// обществознание
						if (!empty($line[27])){
							$first_scobe = strpos($line[27], '(');
							$last_scobe = strrpos($line[27], ')');
							//debug($line[27]);
							$score = substr($line[27],$first_scobe+1,$last_scobe-$first_scobe-1);
							$score = explode(',', $score);
							$social = $score;
						}	
							*/
						$abiturient_arr = array('id' => $abiturient[0]['Abiturient']['id'],
								'egenumber' =>  $egenumber,
								'egeyear' => $egeyear,
								'passport_ser' => $passport_ser,
								'passport_num' => $passport_num,
								'lastname' => $abiturient[0]['Abiturient']['lastname'],
								'firstname' => $abiturient[0]['Abiturient']['firstname'],
								'surname' => $abiturient[0]['Abiturient']['surname'],
								'russian' => $russian,
								'math' => $math,
								'chemistry' => $chemistry,
								'biology' => $biology,
								'history' => $history,
								'social' => $social,
						);
						array_push($abiturients, $abiturient_arr);
					} // если абитуриент найден					
				} // если св-во действительно
				
				
			} // while 
			$this->set('abiturients', $abiturients);	
			$this->set('allerrors', $allerrors);
			//debug($abiturients);
		} // if 
		
		$this->layout = 'blank';
		//$this->render('printfsbinfominimal');
	}	// function 
	
	/**
	 * журнал приема документов
	 * 
	 */
	public function journal (){
 		$this->loadModel('Tgintakeorg');
		
		$tgintakeorgs = $this->Tgintakeorg->find('list');
		
		$this->set(compact('tgintakeorgs')); 
		
		$this->loadModel('Abiturient');
		
		$abiturients = $this->Abiturient->find('all');
		
		$this->set('abiturients', $abiturients);
		$this->layout = 'blank';
	}
	
	/**
	 * сгенерированный файл по абутуриентам для заполнения фис
	 */
	public function fislist () {
		
		
		$this->loadModel('Resulttype');
		$resulttypes = $this->Resulttype->find('list');
		$this->set(compact('resulttypes'));
		
		$this->loadModel('Subject');
		$subjects = $this->Subject->find('list');
		$this->set(compact('subjects'));
		
		$this->loadModel('Profession');
		$professions = $this->Profession->find('list');
		$this->set(compact('professions'));
		
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this-> set(compact('learningforms'));
		
		$this->LoadModel('Learningtype');
		$learningtypes=$this->Learningtype->find('list');
		$this->set(compact('learningtypes'));
		
		$this->loadModel('Tgintakeorg');
		$tgintakeorgs = $this->Tgintakeorg->find('list');
		$this->set(compact('tgintakeorgs'));
		
		
		$this->loadModel('Abiturient');
		
		$educationdoctypes = $this->Abiturient->Educationdoctype->find('list');
		$this->set(compact('educationdoctypes'));
		
		
		$abiturients = $this->Abiturient->find('all'/* , array('conditions' => array('Abiturient.id <100'), 'order' => array('Abiturient.id')) */);
		
		//debug($abiturients);
		
		$this->set('abiturients', $abiturients);
		

		
		$this->layout = 'blank';
	}
	
	/**
	 *  функция обрабатывает xml полученный из фис
	 *   для заполнения справочников
	 * 
	 */
	public function parsexml () {
			$tmp = '
			';
			
			
			$xmlArray = Xml::toArray(Xml::build($tmp));
			//debug($xmlArray);
			//die();
			$this->set('xmlArray', $xmlArray);
			
			$this->layout = 'blank';
	}
/**
 *  генерирует xml для отправки в ФИС для новых записей
 *  выбираем только тех абитуриентов которые были добавлены за прошлый день т.е. created - был вчера  
 */
	
	public function xmltofis() {
		$this->loadModel('Abiturient');
/* 		$today_day = date('d');
		$today_month = date('m');
		$today_year = date('Y');
		
		$day_for_search = 0;
		$month_for_search = 0;
		
		$search_date = '';
		if ($today_day == 1 && $today_month == 7) {
			$day_for_search = 30; // последний день июня
			$month_for_search = 6;
		} else if ($today_day == 1 && $today_month == 8) {
			$day_for_search = 31; // последний день июля
			$month_for_search = 7;
		} else if ($today_day > 1) {
			$day_for_search = $today_day - 1;
			$month_for_search = $today_month;
		} */
		$search_date = date('Y-m-d', strtotime('-4 day'));
/* 		debug($search_date);
		die(); */
		// поиск новых личных дел абитуриентов
		//$search_date = $today_year.'-'.$month_for_search.'-'.$day_for_search;
		$abiturients_ids = $this->Abiturient->find('all', array('conditions' => array('Abiturient.created LIKE' => $search_date.'%',
				//'Abiturient.id <' => 35, // проверка выгрузки 34 дел
				'Abiturient.prepared' => 1,
				'Abiturient.approved' => 1), 'recursive' => -1, 'fields' => array('Abiturient.id')));
		
		$ids = array();
		foreach ($abiturients_ids as $abiturients_id):
			array_push($ids, $abiturients_id['Abiturient']['id']);
		endforeach;

		$abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.id' => $ids)));
		
		$this->set('abiturients', $abiturients);
		//debug($abiturients);
		// поиск измененных личных дел абитуриентов
		$this->loadModel('AbiturientsPrivilege');
		$this->loadModel('AbiturientsPrioritet');
		$this->loadModel('Prioritetdoc');
		$this->loadModel('Privilegedoc');
		$this->loadModel('Relative');
		$this->loadModel('Result');
		$this->loadModel('Selectedprofession');
		$this->loadModel('Targetingintake');
		
		$this->loadModel('Profession');
		$preparedprofessions = array();
		$professions = $this->Profession->find('all', array('recursive' => 0, 'fields' => array('Profession.id')));
		foreach ($professions as $profession):
			$professionsubjects = $this->Profession->ProfessionsSubject->find('all', array('conditions' => array('ProfessionsSubject.profession_id' => $profession['Profession']['id'])/* ,'recursive' => 0 */));
			$standart_profession_subjects = array();	
			foreach ($professionsubjects as $professionsubject):
				array_push($standart_profession_subjects, $professionsubject['ProfessionsSubject']['subject_id']);
			endforeach;
			$preparedprofessions [$profession['Profession']['id']] = $standart_profession_subjects;


			endforeach;
			//debug($preparedprofessions);

		$this->set('preparedprofessions', $preparedprofessions);
		//die();
		
		
		$this->layout = 'blank';
	}
/** ***************************************************************************************************
 *  генерация xml для отправки в ФИС полных данный о приемной комиссии
 *  
 * ***************************************************************************************************/
	public function xmltofisfullpriem() {
		$this->loadModel('Abiturient');
		$this->loadModel('AbiturientsPrivilege');
		$this->loadModel('AbiturientsPrioritet');
		$this->loadModel('Prioritetdoc');
		$this->loadModel('Privilegedoc');
		$this->loadModel('Relative');
		$this->loadModel('Result');
		$this->loadModel('Selectedprofession');
		$this->loadModel('Targetingintake');
		$this->loadModel('Profession');
		
		// выбираем всех абитуриентов
		//$abiturients = $this->Abiturient->find('all');
		//$abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.created <' => '2014-07-26 00:00:00')));
		//$abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.id <=' => '1500')));
		//$abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.id > ' => '1500', 'Abiturient.id <=' => '3114')));
		$abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.id > ' => '3114')));
		//$abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.id' => '3177')));
		$this->set('abiturients', $abiturients);
		//debug($abiturients);
		// поиск измененных личных дел абитуриентов

		
		// создание массива по специальностям со списком предметов по каждой специальности в порядке приоритета
		$preparedprofessions = array();
		$professions = $this->Profession->find('all', array('recursive' => 0, 'fields' => array('Profession.id')));
		foreach ($professions as $profession):
			$professionsubjects = $this->Profession->ProfessionsSubject->find('all', array('conditions' => array('ProfessionsSubject.profession_id' => $profession['Profession']['id'])/* ,'recursive' => 0 */));
			$standart_profession_subjects = array();
			foreach ($professionsubjects as $professionsubject):
				array_push($standart_profession_subjects, $professionsubject['ProfessionsSubject']['subject_id']);
			endforeach;
			$preparedprofessions [$profession['Profession']['id']] = $standart_profession_subjects;
		endforeach;
		//debug($preparedprofessions);
		//debug($abiturients);	
		$this->set('preparedprofessions', $preparedprofessions);
		//die();
		$this->layout = 'blank';		
	}
	
	/** ***************************************************************************************************************
	 * 
	 * функция расчитывает средни бал на специальности и предметы на текущий момент времени по данным базы
	 * 
	 * ***************************************************************************************************************/
	
	public function showprofessionscores () {
		// подключаем модель Educationlevel
		$this->loadModel('Educationlevel');
		$educationlevels = $this->Educationlevel->find('list');
		$this->set('educationlevels', $educationlevels);
		$tmpeducationlevels = $this->Educationlevel->find('all', array('recursive' => -1, 'fields' => array('Educationlevel.id')));
		//$this->set('tmpeducationlevels', $tmpeducationlevels);
		// подключаем модель Facultet
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);	
		//$this->set('tmpfacultets', $tmpfacultets);
		// подключаем модель Profession
		$this->loadModel('Profession');
		$professions =  $this->Profession->find('list');
		$this->set(compact('professions'));
		//$this->set('tmpprofessions', $tmpprofessions);
		// подключаем модель Learningform
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this-> set('learningforms',$learningforms);
		$tmplearningforms = $this->Learningform->find('all', array('recursive' => -1, 'fields' => array('Learningform.id')));
		//$this->set('tmplearningforms', $tmplearningforms);
		// подключаем модель Learningtype
		$this->LoadModel('Learningtype');
		$learningtypes=$this->Learningtype->find('list');
		$this->set('learningtypes',$learningtypes);
		$tmplearningtypes = $this->Learningtype->find('all', array('recursive' => -1, 'fields' => array('Learningtype.id')));
		//$this->set('tmplearningtypes', $tmplearningtypes);
		// подключаем модель Abiturient
		$this->loadModel('Abiturient');
		$abiturients = $this->Abiturient->find('all', array('conditions' => array(
				'Abiturient.prepared' => 1,
				'Abiturient.approved' => 1,
				'Abiturient.enrolled' => 0,
				'Abiturient.canceled' => 0
		
		), 'recursive' => -1, 'fields' => array('Abiturient.id')));
		
		$abiturients_ids = array();
		
		foreach ($abiturients as $abiturient):
			array_push($abiturients_ids, $abiturient['Abiturient']['id']);
		endforeach;
		// подключаем модель Selectedprofession
		$this->loadModel('Selectedprofession');
		$total = array();
		$totalabiturients = array();
		foreach ($tmpeducationlevels as $educationlevel):
			$tmpfacultets = $this->Facultet->find('all', array('conditions' =>array('Facultet.educationlevel_id' => $educationlevel['Educationlevel']['id']), 'recursive' => -1, 'fields' => array('Facultet.id')));
			foreach ($tmpfacultets as $facultet):
			$tmpprofessions = $this->Profession->find('all', array('conditions' =>array('Profession.facultet_id' => $facultet['Facultet']['id']), 'recursive' => -1, 'fields' => array('Profession.id')));
				foreach ($tmpprofessions as $profession):
					foreach ($tmplearningforms as $learningform):
						foreach ($tmplearningtypes as $learningtype):
							$selectedprofession_abi_ids = $this->Selectedprofession->find('all', array('conditions' =>
								array(
										'Selectedprofession.profession_id' => $profession['Profession']['id'],
										'Selectedprofession.abiturient_id' => $abiturients_ids,
										'Selectedprofession.learningform_id' => $learningform['Learningform']['id'],
										'Selectedprofession.learningtype_id' => $learningtype['Learningtype']['id'],
								), 'recursive' =>-1, 'fields' => array('Selectedprofession.abiturient_id')));
			
							$selprof_ids = array();
							foreach ($selectedprofession_abi_ids as $id):
								array_push($selprof_ids, $id['Selectedprofession']['abiturient_id']);
							endforeach;
							
							$totalabiturients['Totalscore'] = '';
							$totalabiturients['profession_id'] = $profession['Profession']['id'];
							$totalabiturients['learningform_id'] =  $learningform['Learningform']['id'];
							$totalabiturients['learningtype_id'] =  $learningtype['Learningtype']['id'];
							$totalabiturients['ids'] = $selprof_ids;
							array_push($total, $totalabiturients);
						endforeach;
					endforeach;
				endforeach;
			endforeach;
		endforeach;

		// создание массива по специальностям со списком предметов по каждой специальности в порядке приоритета
		$preparedprofessions = array();
		$professions = $this->Profession->find('all', array('recursive' => 0, 'fields' => array('Profession.id')));
		foreach ($professions as $profession):
			$professionsubjects = $this->Profession->ProfessionsSubject->find('all', array('conditions' => array('ProfessionsSubject.profession_id' => $profession['Profession']['id'])));
			$standart_profession_subjects = array();
			foreach ($professionsubjects as $professionsubject):
				array_push($standart_profession_subjects, $professionsubject['ProfessionsSubject']['subject_id']);
			endforeach;
			$preparedprofessions [$profession['Profession']['id']] = $standart_profession_subjects;
		endforeach;		
		
		//debug($preparedprofessions);
		// перебор всех заявлений по спицфиальности форме и типу
		$i = 0;
		foreach ($total as $element):
			$ids = $element['ids'];
			$abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.id' => $ids)));
			$scores = 0;
			foreach ($abiturients as $abiturient):
				foreach ($abiturient['Result'] as $result):
						foreach ($preparedprofessions[$element['profession_id']] as $subject_id):
							if ($subject_id == $result['subject_id']) {
								$scores += $result['score'];
							}
						endforeach;		
					//	debug($element);
				endforeach;	
			endforeach;
			//debug($scores/* /count($ids) */);
			$total[$i]['Totalscore']  = $scores;
			
			$i++;
		endforeach;
				
		//debug($total);
		
		$this->set('total', $total);
		$this->layout = 'blank';
	}
	/** ***************************************************************************************************************
	 * 
	 *  выгружает списки целевиков для отсека
	 * 
	 * ***************************************************************************************************************/
	
	public function gzgu() {


		$this->loadModel('Selectedprofession');
		$this->loadModel('Profession');
		$this->loadModel('Abiturient');
		$this->loadModel('Enrolledstudent');
		$this->loadModel('AbiturientsPrivilege');
		$this->loadModel('AbiturientsPrioritet');
		$this->loadModel('Citizenship');
		$citizenships = $this->Citizenship->find('list');
		//$this->set(compact('citizenships'));
		
/* 		$abiturients = $this->AbiturientsPrivilege->find('all', array('conditions' => array('AbiturientsPrivilege.privilege_id' => 4), 'recursive' => -1, 'fields' => array('AbiturientsPrivilege.abiturient_id')));
		
		$abi_ids = array();
		foreach ($abiturients as $abiturient):
			array_push($abi_ids, $abiturient['AbiturientsPrivilege']['abiturient_id']);
		endforeach;
 */		
		//debug(count($abi_ids));
		//die();
		$professions_ids = array(13,14,15,16,17);
		
/* 		$abiturients = $this->Selectedprofession->find('all', array('conditions' => array('Selectedprofession.abiturient_id' => $abi_ids, 
				'Selectedprofession.profession_id' => $professions_ids, 
				'Selectedprofession.learningtype_id' => 1))); */
		
		$abiturients = $this->Enrolledstudent->find('all', array('conditions' => array(
				'Enrolledstudent.profession_id' => $professions_ids,
				)));
		//debug($abiturients);
		//die();
		$count = 0;
		$bcount = 0;
		$mcount = 0;
		//$abi_ids = array();
		foreach($abiturients as $abiturient):
			if ($abiturient['Abiturient']['educationdoctype_id'] == 7) {
				if ($abiturient['Abiturient']['gender_id'] == 1) {
					$bcount++;
				} else {
					$mcount++;
				}
			}
		endforeach;
		//$abiturients = $this->AbiturientsPrivilege->find('all', array('conditions' => array('AbiturientsPrivilege.abiturient_id' => $abi_ids)));
		//debug($abiturients);
		debug($count);
		debug($bcount);
		debug($mcount);
		die();
		$this->layout = 'blank';
	}

/** ******************************************************************
 *  генерация xml для отправки в ФИС заявления на удаление
 */
	public function xmltofisdeleteapp() {
		$this->loadModel('Abiturient');
		$abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.id' => '1843')));
		$this->set('abiturients', $abiturients);
		//debug($abiturients);
		// поиск измененных личных дел абитуриентов
		$this->loadModel('AbiturientsPrivilege');
		$this->loadModel('AbiturientsPrioritet');
		$this->loadModel('Prioritetdoc');
		$this->loadModel('Privilegedoc');
		$this->loadModel('Relative');
		$this->loadModel('Result');
		$this->loadModel('Selectedprofession');
		$this->loadModel('Targetingintake');
		$this->loadModel('Profession');
	
		// создание массива по специальностям со списком предметов по каждой специальности в порядке приоритета
		$preparedprofessions = array();
		$professions = $this->Profession->find('all', array('recursive' => 0, 'fields' => array('Profession.id')));
		foreach ($professions as $profession):
		$professionsubjects = $this->Profession->ProfessionsSubject->find('all', array('conditions' => array('ProfessionsSubject.profession_id' => $profession['Profession']['id'])/* ,'recursive' => 0 */));
		$standart_profession_subjects = array();
		foreach ($professionsubjects as $professionsubject):
		array_push($standart_profession_subjects, $professionsubject['ProfessionsSubject']['subject_id']);
		endforeach;
		$preparedprofessions [$profession['Profession']['id']] = $standart_profession_subjects;
		endforeach;
		//debug($preparedprofessions);
		//debug($abiturients);
		$this->set('preparedprofessions', $preparedprofessions);
		//die();
		$this->layout = 'blank';
	}
	/**
	 *  генерация xml для отправки в ФИС полных данный о приемной комиссии после 25 июля
	 */
	public function xmltofisfullpriem2() {
		$this->loadModel('Abiturient');
		//
		//$abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.created >=' => '2013-07-26')));
		//$abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.created >=' => '2013-08-09')));
		$ids = array(1939, 2620, 2577, 1181);
		$abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.id' => $ids)));
		$this->set('abiturients', $abiturients);
		//debug($abiturients);
		// поиск измененных личных дел абитуриентов
		$this->loadModel('AbiturientsPrivilege');
		$this->loadModel('AbiturientsPrioritet');
		$this->loadModel('Prioritetdoc');
		$this->loadModel('Privilegedoc');
		$this->loadModel('Relative');
		$this->loadModel('Result');
		$this->loadModel('Selectedprofession');
		$this->loadModel('Targetingintake');
		$this->loadModel('Profession');
	
		// создание массива по специальностям со списком предметов по каждой специальности в порядке приоритета
		$preparedprofessions = array();
		$professions = $this->Profession->find('all', array('recursive' => 0, 'fields' => array('Profession.id')));
		foreach ($professions as $profession):
		$professionsubjects = $this->Profession->ProfessionsSubject->find('all', array('conditions' => array('ProfessionsSubject.profession_id' => $profession['Profession']['id'])/* ,'recursive' => 0 */));
		$standart_profession_subjects = array();
		foreach ($professionsubjects as $professionsubject):
		array_push($standart_profession_subjects, $professionsubject['ProfessionsSubject']['subject_id']);
		endforeach;
		$preparedprofessions [$profession['Profession']['id']] = $standart_profession_subjects;
		endforeach;
		//debug($preparedprofessions);
		//debug($abiturients);
		$this->set('preparedprofessions', $preparedprofessions);
		//die();
		$this->layout = 'blank';
	}	
	
	public function otchet() {
		/*$profession_id = 1;
		
		$this->loadModel('Learningform');
		$this->loadModel('Learningtype');
		$this->loadModel('Profession');
		$this->loadModel('Enrolledstudent');
		$this->loadModel('Abiturient');
		$this->loadModel('Selectedprofession');
		
		$professions = array(13,14,15,16,17);
		$abi_ids = array();
		// находим id 
		
		$ids = $this->Enrolledstudent->find('all', array('conditions' => array('Enrolledstudent.profession_id' => $professions), 'recursive' => -1));
		//debug($ids);
		//die();
		foreach ($ids as $id):
			array_push($abi_ids, $id['Enrolledstudent']['abiturient_id']);
		endforeach;
		
		$abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.id' => $abi_ids)));
		
		//debug($abiturients);
		
		$professions = $this->Profession->find('list');
		$this->set(compact('professions'));
		//
		$this->set('abiturients', $abiturients);
		
		//debug($abiturients);
		//die(); */
		
		$this->loadModel('Tgintakeorg');
		$this->loadModel('Targetingintake');
		$orgs = $this->Tgintakeorg->find('all', array('recursive' => -1));
		
		//debug($orgs);
		$results = array();
		foreach ($orgs as $org):
			$is_tgintake = $this->Targetingintake->find('count', array('conditions' => array('Targetingintake.tgintakeorg_id' => $org['Tgintakeorg']['id'])));
			//debug($is_tgintake);
			$result = array('name' => $org['Tgintakeorg']['name'], 'count' => $is_tgintake);
			array_push($results, $result);
		endforeach;
		// debug($results);
		 $this->set('results', $results);
		$this->layout = 'blank';
	}
/**
 * генерация xml документа с зачисленными студентами по приказам
 * 
 */	
	public function xmltofisenrolled() {
		$this->loadModel('Enrolledstudent');
		
		$abiturients = $this->Enrolledstudent->find('all');
		
		$this->set('abiturients', $abiturients);
		
/* 		debug($abiturients);
		die(); */
		
		$this->layout = 'blank';
	}
	
/** *************************************************************************************************
 *  проверка дел абитуриентов перед генерацией xml пакета для фис
 * *************************************************************************************************/
	public function checkbeforefis () {
		$this->loadModel('Abiturient');
		
		// проверка у кого не поставлено гражданство
		$no_citizenship = $this->Abiturient->find('all', array('conditions' => array('Abiturient.citizenship_id' => NULL), 'recursive' => -1, 'fields' =>  array('Abiturient.id')));
		$this->set('no_citizenship', $no_citizenship);
		
		// проверка у кого не поставлен тип документа об образовании
		$no_edudoctype = $this->Abiturient->find('all', array('conditions' => array('Abiturient.educationdoctype_id' => NULL), 'recursive' => -1, 'fields' =>  array('Abiturient.id')));
		$this->set('no_edudoctype', $no_edudoctype);
		
		// проверка у кого не поставлен год окончания школы
		$no_schoolgraduatedyear = $this->Abiturient->find('all', array('conditions' => array('Abiturient.schoolgraduated' => ''), 'recursive' => -1, 'fields' =>  array('Abiturient.id')));
		$this->set('no_schoolgraduatedyear', $no_schoolgraduatedyear);
	}	
/** ***************************************************************************************************************
 * 
 *  вывод номеров личных дел абитуриентов у которых есть инвалидность как приоритет
 *  
 * ***************************************************************************************************************/	
	public function abiturientspp () {
		$this->loadModel('AbiturientsPrioritet');
		
		// 2 инвалиды 14 инвалиды 3 группы
		$ids = array(2,14);
		$abiturients_prioritets = $this->AbiturientsPrioritet->find('all', array('conditions' => array('AbiturientsPrioritet.prioritet_id' => $ids), 'recursive' => -1, 'fields' => array('AbiturientsPrioritet.abiturient_id'), 'order' => 'AbiturientsPrioritet.abiturient_id'));
		$this->set('abiturients_prioritets', $abiturients_prioritets);
		
		$this->loadModel('AbiturientsPrivilege');
		
		// 2 инвалид 
		$ids = array(2);
		$abiturients_privileges = $this->AbiturientsPrivilege->find('all', array('conditions' => array('AbiturientsPrivilege.privilege_id' => $ids), 'recursive' => -1, 'fields' => array('AbiturientsPrivilege.abiturient_id'), 'order' => 'AbiturientsPrivilege.abiturient_id'));
		$this->set('abiturients_privileges', $abiturients_privileges);
	}
/** ***************************************************************************************************************
 * 
 * выводит пофамильный список абитуриентов по специальностям с указанием номера специальности в порядке приоритета
 * 
 * ***************************************************************************************************************/	
	public function abiturientsprioritetsabc () {
		// подключаем модель Educationlevel
		$this->loadModel('Educationlevel');
		$educationlevels = $this->Educationlevel->find('list');
		$this->set('educationlevels', $educationlevels);
		$tmpeducationlevels = $this->Educationlevel->find('all', array('recursive' => -1, 'fields' => array('Educationlevel.id')));
		//$this->set('tmpeducationlevels', $tmpeducationlevels);
		// подключаем модель Facultet
		$this->loadModel('Facultet');
		$facultets = $this->Facultet->find('list');
		$this->set('facultets', $facultets);
		
		//$this->set('tmpfacultets', $tmpfacultets);
		// подключаем модель Profession
		$this->loadModel('Profession');
		$professions =  $this->Profession->find('list');
		$this->set(compact('professions'));
		
		//$this->set('tmpprofessions', $tmpprofessions);
		// подключаем модель Learningform
		$this->loadModel('Learningform');
		$learningforms = $this->Learningform->find('list');
		$this-> set('learningforms',$learningforms);
		$tmplearningforms = $this->Learningform->find('all', array('recursive' => -1, 'fields' => array('Learningform.id')));
		//$this->set('tmplearningforms', $tmplearningforms);
		// подключаем модель Learningtype
		$this->LoadModel('Learningtype');
		$learningtypes=$this->Learningtype->find('list');
		$this->set('learningtypes',$learningtypes);
		$tmplearningtypes = $this->Learningtype->find('all', array('recursive' => -1, 'fields' => array('Learningtype.id')));
		//$this->set('tmplearningtypes', $tmplearningtypes);
		
		// подключаем модель Selectedprofession
		$this->loadModel('Selectedprofession');
		// подключаем модель Abiturient
		$this->loadModel('Abiturient');
		
		$abiturientslist  = array();
		
		foreach ($tmpeducationlevels as $educationlevel):
			$abiturientslist[$educationlevel['Educationlevel']['id']] = array();
			$tmpfacultets = $this->Facultet->find('all', array('conditions' =>array('Facultet.educationlevel_id' => $educationlevel['Educationlevel']['id']), 'recursive' => -1, 'fields' => array('Facultet.id', 'Facultet.educationlevel_id')));
			foreach ($tmpfacultets as $facultet):
				$tmpprofessions = $this->Profession->find('all', array('conditions' =>array('Profession.facultet_id' => $facultet['Facultet']['id']), 'recursive' => -1, 'fields' => array('Profession.id')));
				foreach ($tmpprofessions as $profession):
					$abiturientslist[$educationlevel['Educationlevel']['id']][$profession['Profession']['id']] = array();
					foreach ($tmplearningforms as $learningform):
						$abiturientslist[$educationlevel['Educationlevel']['id']][$profession['Profession']['id']][$learningform['Learningform']['id']] = array();
						foreach ($tmplearningtypes as $learningtype):
							$abiturientslist[$educationlevel['Educationlevel']['id']][$profession['Profession']['id']][$learningform['Learningform']['id']][$learningtype['Learningtype']['id']] = array();
						endforeach;
					endforeach;
				endforeach;
			endforeach;
		endforeach;
		
		//debug ($abiturientslist);
		
		
		$abiturients_ids = $this->Abiturient->find('all', array ('conditions' => array(
				'Abiturient.prepared' => 1,
				'Abiturient.approved' => 1,
				'Abiturient.enrolled' => 0,
				'Abiturient.canceled' => 0
					
		), 'recursive' => -1,'fields' => array('Abiturient.id','Abiturient.lastname', 'Abiturient.firstname', 'Abiturient.surname', 'Abiturient.originaleducationdoc' ) ));
		
		foreach ($abiturients_ids as $abiturient_id):
			$abiturient_selprofs = $this->Selectedprofession->find('all', array('conditions' => array('Selectedprofession.abiturient_id' => $abiturient_id['Abiturient']['id']), 'recursive' => -1, 'order' => 'Selectedprofession.id'));
			
				
			// проверяем есть ли у абитуриента льгота
			$is_privilege = $this->Abiturient->AbiturientsPrivilege->find('count', array('conditions' => array('AbiturientsPrivilege.abiturient_id' =>$abiturient_id['Abiturient']['id'])));
				
			// проверяем есть ли у абитуриента оценки ФЦТ
			$is_fct = $this->Abiturient->Result->find('count', array('conditions' => array('Result.abiturient_id' => $abiturient_id['Abiturient']['id'], 'Result.resulttype_id' => 2)));
				
			
			$first_selprof = 0;
			foreach ($abiturient_selprofs as $selprof):
				$first_selprof++;
				$fio  = $abiturient_id['Abiturient']['lastname'].' '.$abiturient_id['Abiturient']['firstname'].' '.$abiturient_id['Abiturient']['surname'];

				// если льгота
				if (($first_selprof == 1) && $is_privilege) {
					$fio .= ' (вне конкурса)';
				}
				if ($is_fct) {
					$fio .= ' (вступительные испытания в ВУЗе)';
				}
				$edulevel = 0;
				if ($selprof['Selectedprofession']['profession_id'] <13) {
					$edulevel = 1;
				} else {
					$edulevel = 2;
				}
				
				$fio .= '|'.$first_selprof.'|'.$abiturient_id['Abiturient']['originaleducationdoc'];
				array_push($abiturientslist[$edulevel][$selprof['Selectedprofession']['profession_id']][$selprof['Selectedprofession']['learningform_id']][$selprof['Selectedprofession']['learningtype_id']], $fio);
				endforeach;
		endforeach;
		
		
		$this->set('abiturientslist', $abiturientslist);
		
		$this->layout = 'blank';
	}
/** ***************************************************************************************************************
 *
 * выводит абитуриентов которые сдают ФЦТ с указанием предметов которые они сдают
 *
 * ***************************************************************************************************************/	
	public function abiturientsfct() {
		$this->loadModel('Result');
		
		$results = $this->Result->find('all', array('conditions' => array('Result.resulttype_id' => 2)));
		
		$abiturients = array();
		foreach ($results as $result):
			$fio  = $result['Abiturient']['lastname'].' '.$result['Abiturient']['firstname'].' '.$result['Abiturient']['surname'];
			$abiturients[$result['Abiturient']['id']] = array('fio' => $fio, 'subjects' => array());
		endforeach;
		
		foreach ($results as $result):
			array_push($abiturients[$result['Abiturient']['id']]['subjects'], $result['Subject']['name']);
		endforeach;
		
		$this->set('abiturients', $abiturients);
		
		$this->layout = 'blank';
		
	}
	/** ***************************************************************************************************************
	 *
	 * считаем количество заявлений от абитуриентов у которых 100 баллов по непрофильному предмету
	 *  тоесть  олимпиадников по непрофильному предмету
	 *
	 * ***************************************************************************************************************/
	public function gzgu100ballov() {
		$this->loadModel('Result');
		$this->loadModel('Selectedprofession');
		
		$ids = $this->Selectedprofession->find('all', array('conditions' => array('Selectedprofession.profession_id' => 5, 'Selectedprofession.learningform_id' => 3, 'Selectedprofession.learningtype_id' => 2), 'recursive' => -1));
		//debug ($ids);
		foreach ($ids as $id):
			$selprofcount = $this->Selectedprofession->find('count', array('conditions' => array('Selectedprofession.abiturient_id' => $id['Selectedprofession']['abiturient_id'])));
			debug ($id['Selectedprofession']['abiturient_id']);
			debug ($selprofcount);
		endforeach;
			
		die();
/* 		$results = $this->Result->find('all', array('conditions' => array('Result.score' => 100, 'Result.resulttype_id' =>3), 'recursive' => -1));
		
		$abiturients_ids = array();
		foreach ($results as $result):
			array_push($abiturients_ids, $result['Result']['abiturient_id']);
		endforeach;
		$gzgucount = array();
		foreach ($abiturients_ids as $abiturient_id):
			$selprofs = $this->Selectedprofession->find('all', array('conditions' => array('Selectedprofession.abiturient_id' => $abiturient_id), 'recursive' => -1));
			debug($selprofs);
			
		endforeach;
		debug ($abiturients_ids); */
	}	
	/** ***************************************************************************************************************
	 * вывод списка внебюджетников по факультетам по специальностям с сортировкой по уменшению баллов
	 * 
	 * 
	 * ***************************************************************************************************************/
	public function vblist() {
		$this->loadModel('Contract');
		$this->loadModel('Abiturient');
		// получаем список специальностей
		$this->loadModel('Profession');
		$professions = $this->Profession->find('list');
		$this->set(compact('professions'));
		
		$contracts = $this->Contract->find('all', array(/* 'conditions' => array('Contract.paid' => true), */ 'order' => 'Contract.profession_id', 'fields' => array('Contract.profession_id', 'Contract.abiturient_id')));
		
		$contract_abiturients_ids = array();
		// выбираем специальности
		foreach ($contracts as $contract):
			$profession_id = $contract['Contract']['profession_id'];
			$contract_abiturients_ids[$profession_id]= array();
		endforeach;
		// рассовываем id абитуриентов по элементам массива где индекс элемента id специальности
		foreach($contracts as $contract):
			$profession_id = $contract['Contract']['profession_id'];
			array_push($contract_abiturients_ids[$profession_id],  $contract['Contract']['abiturient_id']);
		endforeach;
		
		//debug ($contract_abiturients_ids);
		
		// получаем список предметов
		$this->loadModel('Subject');
		$subjects = $this->Subject->find('list');
		$this->set('subjects', $subjects);		
		
		$global_list = array();
		
		// перебраем все специальности для каждой формируем рейтинг
		 foreach ($contract_abiturients_ids as $key => $value):
		 
			 // получаем id предметов по специальности
			 $this->loadModel('ProfessionsSubject');
			 $subjects_ids = $this->ProfessionsSubject->find('all', array('conditions' => array('ProfessionsSubject.profession_id' => $key)));
			 
			 $profession_subjects = array();
			 foreach ($subjects_ids as $subject):
				 array_push($profession_subjects, $subject['ProfessionsSubject']['subject_id']);
			 endforeach;
		 
		 	// выбираем инфо по абитуриентам	 
			 $abiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.id' => $value),
			 		'recursive' => 1,
			 		'fields' => array ('Abiturient.id',
			 				'Abiturient.lastname',
			 				'Abiturient.firstname',
			 				'Abiturient.surname',
			 )));
			
			 $allabiturients_ids = array();
		 	// считаем сумму баллов по специальности
		 	$score_total_abiturients = array(); // к данным абитуриента добавлен елемент Score_total
		 	foreach ($abiturients as $abiturient):
		 		// запоминаем id абитуриента
		 		array_push($allabiturients_ids, $abiturient['Abiturient']['id']);
		 		// считаем  сумму балов по специальности
		 		$score_total = 0;
		 		foreach ($subjects_ids as $subject_id):
		 			foreach ($abiturient['Result'] as $result):
						 if ($subject_id['ProfessionsSubject']['subject_id'] == $result['subject_id']){
						 	$score_total += $result['score'];
						 }
		 			endforeach;
		 		endforeach;
				 $abiturient['Score_total'] = $score_total;
		 		array_push($score_total_abiturients, $abiturient);
		 	endforeach;
		 
		 	// начинаем разбирать абитуриентов в  массив с сортровкой по рейтингу
		 	$arr_plain_scoretotal_ids = array();
		 	foreach ($score_total_abiturients as $abiturient):
		 		$arr_plain_scoretotal_ids[$abiturient['Abiturient']['id']] = $abiturient['Score_total'];
		 	endforeach;
		 	// сортируем массив по убыванию	Score_total
		 	arsort($arr_plain_scoretotal_ids);
		 	
		 	$plain_abiturients = array();
		 	
		 	array_push($plain_abiturients, array('sortedabiturients_ids' => $arr_plain_scoretotal_ids));
		 	
		 	// получаем описание нужных абитуриентов
		 	$allabiturients = $this->Abiturient->find('all', array('conditions' => array('Abiturient.id' => $allabiturients_ids)));
		 	//debug($allabiturients);
		 	
		 	$tmpgloballist = array('profession' => '', 'allabiturients' => array(), 'sorted_abiturients' => array());
		 	$tmpgloballist['allabiturients'] = $allabiturients;
		 	$tmpgloballist['sorted_abiturients'] = $plain_abiturients;
		 	$tmpgloballist['profession_id'] = $key;
		 	$tmpgloballist['subjects_ids'] = $subjects_ids;
		 	$tmpgloballist['profession_subjects'] = $profession_subjects;
		 	array_push($global_list, $tmpgloballist);

		 endforeach;
		 //debug ($global_list);
		// die();
			$this->set('globallist', $global_list);
			
			$this->layout = 'blank';
	}
/** ************************************************************************************************************** 
 *  перебираем зачисленных студентов перемещая их фото в отдельную папку
 *  для дальнейшей печати карт доступа
 * 
 *  ***************************************************************************************************************/	
	public function getphotoes() {
		$this->loadModel('Enrolledstudent');
		$students = $this->Enrolledstudent->find('all', array('conditions' => array('Enrolledstudent.profession_id >' => 12)));
		$i = 0;
		foreach ($students as $student):
		 
			$source = iconv('UTF-8', 'Windows-1251','img/photo/'.$student['Enrolledstudent']['abiturient_id'].'.jpg') ;
			$dest = iconv('UTF-8', 'Windows-1251', 'img/enrolledphoto/'.$student['Profession']['name'].' '.$student['Learningform']['name'].' '.$student['Learningtype']['name'].' '.$student['Abiturient']['lastname'].' '.$student['Abiturient']['firstname'].' '.$student['Abiturient']['surname'].'.jpg') ;
			if (file_exists($source)) {
				copy($source , $dest) or die('no copy');
				$i++;
			}

		endforeach;
		debug($i);
		die();
	}
}
